<?php

global $user, $administrator, $current_user, $usr_id, $blogurl;
global $rem_url, $rem_port, $rem_id, $usr_username;

require_once ( get_template_directory() . '/custom_fields.php' );
require_once ( get_template_directory() . '/main_settings.php' );
require_once ( get_template_directory() . '/new_user.php' );



define('TEMPLATE_PATH_CSS', get_template_directory());
define('CSS_DOMAIN','css');

add_role( 'user', 'User' );

$user = get_role('user');
$administrator = get_role('administrator');

$current_user = css_wp_get_current_user();
$usr_id = $current_user->ID;
$usr_username = $current_user->user_login;

$blogurl = get_bloginfo( 'url' );

$administrator->add_cap('manage_options');
$administrator->add_cap('manage_access');
$administrator->add_cap('manage_assisted');
$administrator->add_cap('view_access');
$administrator->add_cap('view_assisted');
				
$user->add_cap('view_access');	
$user->add_cap('view_assisted');
$user->add_cap('edit_users');
$user->add_cap('list_users'); 

$rem_url = 'http://195.128.234.70';
$rem_port = '8080';


add_action('wp_head', 'get_remote_id_javascript');
function get_remote_id_javascript() {
?>
<script type="text/javascript" >
	
	<?php global $usr_username; ?>
	jQuery(document).ready(function() {		
		get_remote_id_javascript('<?php echo $usr_username; ?>');		
	});

	function get_remote_id_javascript(username) {	

		<?php global $rem_url, $rem_port; ?>
				
		var url = '<?php echo $rem_url ?>' + ':' + '<?php echo $rem_port ?>' + '/webservice/LoginServlet?username=' + username;
		
	    $.ajax({
	        url: url,
	        //dataType: "json",
	        async: true,
	        success: function (result) {
		        
	        	var data = {
        			action: 'get_remote_id',			
        			rem_id: result        			
        		};

	        	jQuery.post(ajaxurl, data, function(response) {	    			
	        			
	    		});
	        		        	
	        },
	        error: function (request,error) {
	            alert('An User error has occurred, please try again!');
	        }
	    });
		
	}
	
</script>
<?php
}


add_action('wp_ajax_get_remote_id', 'get_remote_id_callback');
add_action('wp_ajax_nopriv_get_remote_id', 'get_remote_id_callback');
function get_remote_id_callback() {	
	
	global $usr_id;	
	
	$rem_id = get_user_meta($usr_id, 'rem_id', true);
	
	if ($rem_id && $rem_id != "" && $rem_id != "0") {
		// do nothing
	} else {
		update_user_meta( $usr_id, 'rem_id', $_POST['rem_id']);
	}
	
	echo $rem_id;
	die();
	
}



$rem_id = get_user_meta($usr_id, 'rem_id', true);